package com.itheima.dubbo.mongodb.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.Publish;
import com.itheima.commons.pojo.TimeLine;
import com.itheima.dubbo.interfaces.PublishApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @ClassName: PublishApiImpl
 * @Description:
 * @Author: Administrator
 * @Date: 2021/12/8 10:39
 */
@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public String publish(Publish publish) {
         mongoTemplate.save(publish);
        //publish会被重新赋值
        return publish.getId().toHexString();
    }

    @Override
    public List findPublish(Long userId, Integer page, Integer pagesize,Class type) {

        List<TimeLine> timeLines = mongoTemplate.find(new Query(), TimeLine.class, Constants.TIME_LINE_PRE_ + userId);
        //把时间线中的id封装到集合中
        List<Object> publishId = CollUtil.getFieldValues(timeLines, "publishId");

        List publishList = mongoTemplate.find(Query.query(Criteria.where("id").in(publishId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page, pagesize)), type);
        return publishList;
    }

    @Override
    public List<?> random(Integer pagesize,Class<?> type) {
        // 从MongoDB中随机抽样数据
        AggregationResults<?> aggregationResults = mongoTemplate.aggregate(Aggregation.newAggregation(type, Aggregation.sample(Convert.toLong(pagesize))),
                type);
        List<?> mappedResults = aggregationResults.getMappedResults();
        return mappedResults;
    }

    @Override
    public List<Publish> findPublishByPidList(List<Long> pidsList) {
        List<Publish> publishList = mongoTemplate.find(Query.query(Criteria.where("pid").in(pidsList)), Publish.class);
        return publishList;
    }

    @Override
    public Publish findPublish(ObjectId publishid) {
        Publish publish = mongoTemplate.findOne(Query.query(Criteria.where("id").is(publishid)), Publish.class);
        return publish;
    }

    @Override
    public List<Publish> findPublishByuserId(Long userId, Integer page, Integer pageSize) {
        return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Publish.class);

    }
}
